//
//  HomeViewController.m
//  DuBai
//
//  Created by darktm on 14-2-23.
//  Copyright (c) 2014年 darktm. All rights reserved.
//

#import "HomeViewController.h"

#import "SearchResultViewController.h"
#import "SVWebViewController.h"
#import "CommodityDetailViewController.h"


#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"

#import "HomeViewCell.h"
#import "HomeSearchView.h"
#import "SVPullToRefresh.h"

#import "BaseImageView.h"
#import "TaskWithGetHomeAd.h"
#import "TaskWithGetRecommend.h"
#import "TaskWithSetDefaultLocal.h"

#import "AdObject.h"
#import "RecommendObject.h"

#import "LoginViewController.h"

#define kSearchTag 100000
#define kAdTag 1000

@interface HomeViewController ()<WYHttpTaskDelegate,HomeSearchViewDelegate>

@property(strong,nonatomic)NSArray *adArray;
@property(strong,nonatomic)NSMutableArray *recommentArray;

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view
    
    
    _recommentArray = [NSMutableArray array];
    _adArray = [NSArray array];
    self.srv.backgroundColor = [UIColor darkGrayColor];
    
    DLog(@"%.2f",kHeight);
    
#warning 不能和cellForItemAtIndexPath中的ReuseIdentifier一样
    [self.cv registerClass:[HomeViewCell class] forCellWithReuseIdentifier:@"my_cell"];
    
    
    __weak HomeViewController *weakSelf = self;
    [self.cv addPullToRefreshWithActionHandler:^{
        [weakSelf refreshNew];
    } position:SVPullToRefreshPositionTop];
    
    [self.cv addInfiniteScrollingWithActionHandler:^{
        [weakSelf loadMore];
    }];
    //当没有更多的时候设置
//    self.cv.showsInfiniteScrolling = NO;
    
//    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(100, 15, 100, 30)];
//    v.backgroundColor = [UIColor redColor];
//    [self.cv.infiniteScrollingView setCustomView:v forState:SVInfiniteScrollingStateLoading];
    
    [self loadAd];
    
    [self.cv triggerPullToRefresh];

    self.cv.backgroundColor = [UIColor whiteColor];
    
    [self setDefaultLocal];
}

-(void)setDefaultLocal{
    
    NSString *session = [[NSUserDefaults standardUserDefaults] valueForKey:@"session"];
    if(session) return;
    TaskWithSetDefaultLocal *de = [[TaskWithSetDefaultLocal alloc] init];
    de.delegate = self;
    de.localType = @"cn";
    [de start];
}

-(void)loadAd{
    TaskWithGetHomeAd *ad = [[TaskWithGetHomeAd alloc] init];
    ad.delegate = self;
    [ad start];
}

#pragma mark - pull action -
//加载更多
-(void)loadMore{
    
    TaskWithGetRecommend *recomend = [[TaskWithGetRecommend alloc] init];
    recomend.delegate = self;
    
    if(_recommentArray.count){
        RecommendObject *r = [_recommentArray lastObject];
        recomend.updatetime = r.updatetime;
    }else{
//        recomend.updatetime = @"0";
    }

    [recomend start];
}
//刷新
-(void)refreshNew{
    TaskWithGetRecommend *recomend = [[TaskWithGetRecommend alloc] init];
    recomend.delegate = self;
//    recomend.updatetime = @"0";
    [recomend start];
}


//刷新广告
-(void)refreshSrv{
    
    for (int i = 0; i < [_adArray count]; i++) {
        
        AdObject *obj = _adArray[i];
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(i * 320, 0, 320, 165)];
        btn.tag = kAdTag + i;
        [btn setBackgroundImageWithURL:[NSURL URLWithString:obj.image] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(on_btn_ad:) forControlEvents:UIControlEventTouchUpInside];
        [self.srv addSubview:btn];
    }
    
    self.pageControl.numberOfPages = _adArray.count;
    self.pageControl.currentPage = 0;
    self.pageControl.center = CGPointMake(160, self.pageControl.center.y);
    
    self.srv.pagingEnabled = YES;
    self.srv.contentSize = CGSizeMake(320 * _adArray.count, 1);
    if(_adArray.count > 1)
        [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(on_timer_change_ad:) userInfo:nil repeats:YES];
}

#pragma mark - UICollectionView delegate -

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    int count = ceilf(_recommentArray.count/2.0);
    
    if(section == count - 1)
        return  _recommentArray.count - 2 * section;
    
    return 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor lightGrayColor];
   
    int index = indexPath.section * 2 + indexPath.item;
    

    RecommendObject *object = _recommentArray[index];

    [cell.image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:object.image]]];
    cell.name.text = object.desc;

    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return ceilf(_recommentArray.count/2.0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    int index = indexPath.section * 2 + indexPath.item;
    RecommendObject *obj = _recommentArray[index];
    NSString *channel = [obj.channel lowercaseString];

    DLog(@"%@",obj.link);
    
    if([channel isEqualToString:@"goods"]){
        
        CommodityDetailViewController *detail = (CommodityDetailViewController*)[Utils storyBoardWithId:@"CommodityDetailViewController"];
//        detail.goodid = obj.id;
        detail.goodid = obj.link;
        [self.navigationController pushViewController:detail animated:YES];
    }else if ([channel isEqualToString:@"hotel"]){
        [self loadWebWithUrl:obj.link];
    }else if ([channel isEqualToString:@"diner"]){
        [self loadWebWithUrl:obj.link];
    }else if ([channel isEqualToString:@"travel"]){
        [self loadWebWithUrl:obj.link];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - http delegate -

-(void)requestCompleteWithObj:(WYHttpTask *)obj{

    id rsult = [obj parese];
    
    if([obj isKindOfClass:[TaskWithGetHomeAd class]]){
        _adArray = rsult;
        [self refreshSrv];
    }else if ([obj isKindOfClass:[TaskWithGetRecommend class]]){
    
        if(self.cv.infiniteScrollingView.state == SVInfiniteScrollingStateLoading){
            
        }else if(self.cv.pullToRefreshView.state == SVPullToRefreshStateLoading){
            
            [_recommentArray removeAllObjects];
        }
        
        NSMutableArray *r = rsult;
        if(r.count){
            
            [_recommentArray addObjectsFromArray:r];
            [self.cv reloadData];
        }else{
            DLog(@"没有更多数据");
            
            MBProgressHUDManager  *hud = [[MBProgressHUDManager alloc] initWithView:self.view];
            [hud showMessage:@"没有更多数据...." duration:.3];
        }
    }else if([obj isKindOfClass:[TaskWithSetDefaultLocal class]]){
        
    }
    
    [self.cv.infiniteScrollingView stopAnimating];
    [self.cv.pullToRefreshView stopAnimating];

}
-(void)requestFailWithMsg:(WYHttpTask *)obj{
    DLog(@"%@",obj.networkOp.url);
    [self.cv.infiniteScrollingView stopAnimating];
    [self.cv.pullToRefreshView stopAnimating];
}


#pragma mark - timer repeate -
-(void)on_timer_change_ad:(NSTimer *)timer{
    
    int count = _adArray.count;
    int cur = self.pageControl.currentPage;
    ++cur;
    cur = cur % count;
    self.pageControl.currentPage = cur;
    [self.srv setContentOffset:CGPointMake(320 * cur, 0) animated:YES];
}

#pragma mark - on btn -

-(void)on_btn_ad:(UIButton *)btn{
    int tag = btn.tag - kAdTag;
    AdObject *object = _adArray[tag];
    
    NSString *linktype = [object.linktype lowercaseString];
    
    if([linktype isEqualToString:@"outurl"]){
        NSURL *URL = [NSURL URLWithString:object.link];
        SVWebViewController *webViewController = [[SVWebViewController alloc] initWithURL:URL];
        [self.navigationController pushViewController:webViewController animated:YES];
    }else if([linktype isEqualToString:@"goods"]){

        CommodityDetailViewController *detail = (CommodityDetailViewController*)[Utils storyBoardWithId:@"CommodityDetailViewController"];
        detail.goodid = object.link;
        [self.navigationController pushViewController:detail animated:YES];
        
    }else if ([linktype isEqualToString:@"hotel"]){
        [self loadWebWithUrl:object.link];
    }else if([linktype isEqualToString:@"diner"]){
        [self loadWebWithUrl:object.link];
    }else if([linktype isEqualToString:@"travel"]){
        [self loadWebWithUrl:object.link];
    }else if([linktype isEqualToString:@"fashionInfo"]){
        [self loadWebWithUrl:object.link];
    }
}

- (IBAction)on_btn_hotel:(id)sender {
//    CommodityDetailViewController *detail = (CommodityDetailViewController*)[Utils storyBoardWithId:@"CommodityDetailViewController"];
//    [self.navigationController pushViewController:detail animated:YES];
//    
//    
//    return;
    NSURL *URL = [NSURL URLWithString:@"http://www.baidu.com"];
	SVWebViewController *webViewController = [[SVWebViewController alloc] initWithURL:URL];
	[self.navigationController pushViewController:webViewController animated:YES];
}

- (IBAction)on_btn_restaurant:(id)sender {
    NSURL *URL = [NSURL URLWithString:@"http://www.baidu.com"];
	SVWebViewController *webViewController = [[SVWebViewController alloc] initWithURL:URL];
	[self.navigationController pushViewController:webViewController animated:YES];
}

- (IBAction)on_btn_fashion:(id)sender {
    NSURL *URL = [NSURL URLWithString:@"http://www.baidu.com"];
	SVWebViewController *webViewController = [[SVWebViewController alloc] initWithURL:URL];
	[self.navigationController pushViewController:webViewController animated:YES];
}

- (IBAction)on_btn_tr:(id)sender {
    NSURL *URL = [NSURL URLWithString:@"http://www.baidu.com"];
	SVWebViewController *webViewController = [[SVWebViewController alloc] initWithURL:URL];
	[self.navigationController pushViewController:webViewController animated:YES];
}

- (IBAction)on_btn_search:(id)sender {
    UINavigationController *n = [Utils storyBoardWithId:@"LoginNavigationViewController"];
    [self presentViewController:n animated:YES completion:NULL];
    
    return;
    if([self.tabBarController.view viewWithTag:kSearchTag]) return;
    
    float oy = bVersion7 ? 64 : 44;
    
    CGRect frame = CGRectMake(0, oy, kWidth, kHeight - 64);

    HomeSearchView *s = [[HomeSearchView alloc] initWithFrame:frame];
    s.backgroundColor = [UIColor blackColor];
    s.alpha = .6f;
    s.delegate = self;
    
    s.tag = kSearchTag;
    [self.tabBarController.view addSubview:s];
}

#pragma mark - home search delegate -

-(void)didCancle:(HomeSearchView *)sv{
    
    [UIView animateWithDuration:.2 animations:^{
        sv.alpha = 0;
    } completion:^(BOOL finished) {
        [sv removeFromSuperview];
    }];
}
-(void)didSearch:(HomeSearchView *)sv{
    
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SearchResultViewController *s = [board instantiateViewControllerWithIdentifier:@"SearchResultViewController"];
    s.key = sv.sb.text;
    [self.navigationController pushViewController:s animated:YES];
    
    sv.delegate = nil;
    [sv removeFromSuperview];
}

#pragma mark - private method -

-(void)loadWebWithUrl:(NSString *)url{
    NSURL *URL = [NSURL URLWithString:url];
	SVWebViewController *webViewController = [[SVWebViewController alloc] initWithURL:URL];
	[self.navigationController pushViewController:webViewController animated:YES];
}

@end
